#include "file_manager.h"
#include "dirty_list.h"
#include "uvlog.h"

int DirtyList::update(Page* page)
{
	if(page->dirtyPos != lp.end()){
		lp.erase(page->dirtyPos);
		lp.push_back(page);
		page->dirtyPos = --lp.end();
	}
	else{		
		lp.push_front(page);
		page->dirtyPos = lp.begin();
	}

	return 0;
}

int DirtyList::remove(Page* page)
{	
	if(page->dirtyPos != lp.end()){
		lp.erase(page->dirtyPos);
		page->dirtyPos = lp.end();
	}

	return 0;
}

int DirtyList::flush(){
	int i  = 0;
	while(!lp.empty() && i++ < DIRTY_PER_FLUSH_PAGES){
		Page* page = lp.back();
		lp.pop_back();

		page->dirtyPos = lp.end();
		page->flush();
	}

	//LOG_DEBUG("flush %d pages to disk",i);
	return 0;
}

int DirtyList::flushAll(){
	
	int j = 0;

	while(!lp.empty()){
		Page* page = lp.back();
		lp.pop_back();

		page->dirtyPos = lp.end();
		page->flush();
		++j;
	}
	
	LOG_INFO("flush %d pages to disk",j);
	
	return 0;
}


DirtyList::~DirtyList(){
	flushAll();
}

